namespace Leey.Net.eTerm
{
    using System;
    using System.Text;
    using System.Text.RegularExpressions;

    public class Command
    {
        public static string BytesToString(byte[] data)
        {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                builder.Append(data[i].ToString("X2") + " ");
                if (((i + 1) % 0x10) == 0)
                {
                    builder.Append("\r\n");
                }
            }
            return builder.ToString();
        }

        public static string BytesToString(byte[] data, int length)
        {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < length; i++)
            {
                builder.Append(data[i].ToString("X2") + " ");
                if (((i + 1) % 0x10) == 0)
                {
                    builder.Append("\r\n");
                }
            }
            return builder.ToString();
        }

        public static unsafe string BytesToString(byte* data, int length)
        {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < length; i++)
            {
                data++;
                builder.Append(data[0].ToString("X2") + " ");
                if (((i + 1) % 0x10) == 0)
                {
                    builder.Append("\r\n");
                }
            }
            return builder.ToString();
        }

        public static byte[] CopyBytesBlock(byte[] b, int count)
        {
            byte[] destinationArray = new byte[count];
            Array.Copy(b, 0, destinationArray, 0, count);
            return destinationArray;
        }

        public static byte[] StringToBytes(string s)
        {
            string[] strArray = Regex.Split(Regex.Replace(s, @"[\s\r\n]", " ").Trim(), @"\s{1,5}");
            byte[] buffer = new byte[strArray.Length];
            for (int i = 0; i < strArray.Length; i++)
            {
                buffer[i] = Convert.ToByte(strArray[i], 0x10);
            }
            return buffer;
        }
    }
}
